package com.cykj.filters;

import com.alibaba.fastjson.JSON;
import com.cykj.dto.ResponseDTO;
import com.cykj.utils.JwtUtil;
import org.apache.http.HttpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @author 王宇
 * @CreateTime: 2025-07-25  9:23
 * @BelongsProject: jd-seckill
 * @BelongsPackage: com.cykj.filters
 * @description 登录拦截器
 */
@Component
public class LoginFilter implements GlobalFilter {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    // Mono：异步处理
    // exchange：获取请求消息和响应消息
    // chain：链式处理，多个拦截器通过链连接
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 设置白名单
        String[] urlWhite = {
                "/jd/cli/user/login",
                "/jd/cli/user/register",
                "/jd/sys/admin/login",
                "/jd/cli/good/getGoodList",
        };

        // 检查访问地址是否在白名单内，是就放行，不是就要进一步判断
        String url = exchange.getRequest().getURI().getPath();
        System.out.println("url: " + url);
        for (String s : urlWhite) {
            if (url.contains(s)) {
                System.out.println("在白名单");
                return chain.filter(exchange);
            }
        }
        System.out.println("不在白名单内");

        // 获取请求头的token，如果没有就提示，否则放行
        List<String> strings = exchange.getRequest().getHeaders().get("X-Token");
        String jwtToken = "";
        if (strings == null || strings.isEmpty()) {
            // 如果未携带token
            System.out.println("未携带token");
            ResponseDTO responseDTO = ResponseDTO.error(401, "请携带token");
            return handleUnauthorized(exchange, responseDTO);
        }

        // 判断token是否已经过期
        jwtToken = strings.get(0);
        System.out.println("token: " + jwtToken);
        try {
            JwtUtil.parseJWT(jwtToken);
        } catch (Exception e) {
            System.out.println("token已过期");
            ResponseDTO responseDTO = ResponseDTO.error(401, "token已过期");
            return handleUnauthorized(exchange, responseDTO);
        }

        // 获取redis里的token看看redis里的token是否已经过期
        if (!redisTemplate.hasKey(jwtToken)) {
            // 如果不存在或已经过期
            System.out.println("token已过期或不存在");
            ResponseDTO responseDTO = ResponseDTO.error(401, "token已过期或不存在");
            return handleUnauthorized(exchange, responseDTO);
        }

        // 上述都没问题，就更新redis里token有效期
        redisTemplate.opsForValue().set(jwtToken, Objects.requireNonNull(redisTemplate.opsForValue().get(jwtToken)), 30, TimeUnit.MINUTES);
        return chain.filter(exchange);
    }

    // 添加处理未授权访问的方法
    private Mono<Void> handleUnauthorized(ServerWebExchange exchange, ResponseDTO responseDTO) {
        ServerHttpResponse response = exchange.getResponse();
        // 响应正文
        DataBuffer wrap = response.bufferFactory().wrap(JSON.toJSONBytes(responseDTO));
        // 响应状态码
        response.setStatusCode(HttpStatus.UNAUTHORIZED);  // 401
        // 响应头媒体类型
        response.getHeaders().add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
        // 响应消息
        return response.writeWith(Mono.just(wrap));
    }
}
